<template>
	<view class="test-container">
		<uni-section title="车辆信息" type="line">
			<view class="base-form">
				<view class="base-form-item">车架号：
					<span class="base-form-item-value">{{ baseInfo.vin }}</span>
				</view>
				<view class="base-form-item">车型：
					<span class="base-form-item-value">{{ baseInfo.hpzl }}</span>
				</view>
				<view class="base-form-item">车牌号：
					<span class="base-form-item-value">{{ baseInfo.hphm }}</span>
				</view>
				<view class="base-form-item">里程表：
					<sapn class="base-form-item-value">{{ baseInfo.lCb }}</sapn>
				</view>
			</view>
		</uni-section>

		<uni-section title="车辆照片（一次性最多9张）" type="line">
			<view style="padding: 0 20rpx">
				<up-upload :fileList="fileList" @afterRead="afterRead" @delete="deletePic" name="3" multiple
					:maxCount="1000" :previewFullImage="true"></up-upload>
			</view>
		</uni-section>

		<view class="btns">
			<view class="bnts-audit">
				<view class="item reject" @click="reject"> 车辆驳回 </view>
				<view class="item insc" @click="insc"> 内检完成 </view>
				<view class="item party" @click="party"> 第三方完成 </view>
			</view>
		</view>
	</view>
</template>

<script>
import {
	getVehcileIdOne,
	updateCarStatus,
	getVehicleJCPhoto,
	deleteVehicleJCPhoto,
	addFile
} from '@/api/app.js'
export default {
	data() {
		return {
			baseInfo: {},
			id: '',
			fileList: []
		}
	},
	onLoad(opt) {
		if (opt.id) {
			this.id = opt.id
			this.getVehcileIdOne()
			this.getVehicleJCPhoto()
		}
	},
	methods: {
		async afterRead(file) {
			console.log('file', file)
			const files = file.file
			console.log('files', files)

			// 显示加载提示
			uni.showLoading({
				title: '上传中...',
				mask: true
			})

			try {
				// 创建上传任务数组
				const uploadTasks = files.map(item => {
					return new Promise((resolve, reject) => {
						uni.uploadFile({
							url: 'https://api.weijiashangejiance.com/api/VehiclePhoto/Upload2', //仅为示例，非真实的接口地址
							filePath: item.url,
							name: 'file',
							formData: {
								user: 'test'
							},
							success: (uploadFileRes) => {
								try {
									const resp = JSON.parse(uploadFileRes.data)
									if (resp.code === 1) {
										const key = Object.keys(resp.data)[0]
										const value = resp.data[key]
										resolve({
											path: value,
											url: key,
											status: false,
											vehicleInfoId: this.id
										})
									} else {
										reject(new Error('上传失败: ' + resp.msg))
									}
								} catch (e) {
									reject(new Error('解析响应失败'))
								}
							},
							fail: (err) => {
								console.log('上传失败', err)
								reject(err)
							}
						})
					})
				})

				// 等待所有上传任务完成
				const uploadResults = await Promise.all(uploadTasks)
				
				// 批量添加文件信息
				const add = await addFile(uploadResults)
				if (add.code === 1) {
					// 重新获取图片列表
					await this.getVehicleJCPhoto()
					uni.showToast({
						title: '上传成功',
						icon: 'success'
					})
				} else {
					throw new Error('添加文件信息失败')
				}
			} catch (error) {
				console.error('上传过程发生错误:', error)
				uni.showToast({
					title: '上传失败，请重试',
					icon: 'none'
				})
			} finally {
				// 隐藏加载提示
				uni.hideLoading()
			}
		},
		async deletePic(file) {
			console.log(this.fileList[file.index])
			if (file) {
				const item = this.fileList[file.index]
				await deleteVehicleJCPhoto(item)
				this.fileList.splice(file.index, 1)
				await this.getVehicleJCPhoto()
			}
		},
		// 车辆信息
		async getVehcileIdOne() {
			const res = await getVehcileIdOne({
				id: this.id
			})
			if (res.code === 1) {
				this.baseInfo = res.data
			}
		},
		// 车辆图片
		async getVehicleJCPhoto() {
			const res = await getVehicleJCPhoto({
				id: this.id
			})
			if (res.code === 1) {
				this.fileList = res.data.map((item) => {
					return {
						type: 'image', // 文件类型，image/video/file
						...item,
						url: 'http://www.weijiashangejiance.com' + item.url
					}
				})
			}
		},
		handleEdit() {
			delete this.baseInfo.vehicleJCPhotos
			delete this.baseInfo.vehiclePhotos
			delete this.baseInfo.infoFiles
			this.baseInfo.isJC = false
			this.baseInfo.jcId = 0
			this.baseInfo.isDel = true
			this.baseInfo.isZb = false
			this.baseInfo.zbId = 0
		},
		// 驳回车辆
		reject() {
			uni.showModal({
				title: '提示',
				content: '确定驳回车辆吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit()
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		},
		insc() {
			uni.showModal({
				title: '提示',
				content: '确定内检完成吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit()
						this.baseInfo.jyxm = '内检'
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		},
		party() {
			uni.showModal({
				title: '提示',
				content: '确定第三方检测完成吗？',
				success: async (res) => {
					if (res.confirm) {
						this.handleEdit()
						this.baseInfo.isJC = true
						this.baseInfo.jcId = uni.getStorageSync('id')
						const resp = await updateCarStatus(this.baseInfo)
						if (resp.code === 1) {
							uni.navigateBack()
						}
					} else if (res.cancel) {
						console.log('用户点击取消')
					}
				}
			})
		}
	}
}
</script>

<style scoped lang="scss">
.test-container {
	padding: 20rpx;

	.base-form {
		padding: 0 20rpx 20rpx;

		.base-form-item {
			font-size: 26rpx;
			font-weight: bold;
			line-height: 50rpx;

			.base-form-item-value {
				font-size: 24rpx;
			}
		}
	}

	.btns {
		position: fixed;
		bottom: 30rpx;
		left: 0;
		width: 100%;

		.bnts-audit {
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding: 0 30rpx;

			.item {
				flex: 1;
				text-align: center;
				color: #ffffff;
				padding: 20rpx 0;
				border-radius: 13rpx;
			}

			.reject {
				background-color: #f56c6c;
			}

			.insc {
				margin: 0 30rpx;
				background-color: #07c160;
			}

			.party {
				background-color: #1989fa;
			}
		}
	}
}
</style>